package com.jl.encrypt;

import com.jl.encrypt.config.SecretKeyConfig;
import com.jl.encrypt.util.AESUtils;
import com.jl.encrypt.util.RSAUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

/**
 * 解密处理
 */
@Slf4j
public class JHttpInputMessage implements HttpInputMessage {

    private HttpHeaders headers;

    private InputStream body;

    public JHttpInputMessage(org.springframework.http.HttpInputMessage inputMessage, SecretKeyConfig.AES aes, SecretKeyConfig.RSA rsa, boolean showLog) throws Exception {
        this.headers = inputMessage.getHeaders();
        String content = new BufferedReader(new InputStreamReader(inputMessage.getBody())).lines().collect(Collectors.joining(System.lineSeparator()));
        String decryptBody = content;
        if (content.startsWith("{")) {
            if (showLog) {
                log.info("原文参数未加密");
            }
        } else {
            try {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = requestAttributes.getRequest();
                String iv = request.getHeader("iv");
                StringBuilder json = new StringBuilder();
                content = content.replaceAll(" ", "+");
                if (!StringUtils.isEmpty(content)) {
                    String[] contents = content.split("\\|");
                    for (String value : contents) {
                        value = aes == null ? RSAUtils.privateDecode(value, rsa.getPrivateKey()) : AESUtils.decode(value, aes.getKey(), iv);
                        json.append(value);
                    }
                }
                decryptBody = json.toString();
                if (showLog) {
                    log.info("原文参数：{}, 解密参数：{}", content, decryptBody);
                }
            } catch (Exception e) {
                log.error("解密异常：{}", e);
            }
        }
        this.body = new ByteArrayInputStream(decryptBody.getBytes());
    }

    @Override
    public InputStream getBody() {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }
}
